package com.example.stray_animal_management_system.admin.controller;

import com.example.stray_animal_management_system.entity.RescueStory;
import com.example.stray_animal_management_system.volunteer.service.RescueStoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/1
 */
@RestController
@RequestMapping("/api/admin/story")
public class RescueAdminStoryController {

    @Autowired
    private RescueStoryService rescueStoryService;

    /**
     * 查询故事（按动物ID）
     */
    @GetMapping("/list")
    public Map<String, Object> list(@RequestParam("animalId") Integer animalId) {
        Map<String, Object> res = new HashMap<>();
        List<RescueStory> list = rescueStoryService.lambdaQuery()
                .eq(RescueStory::getAnimalId, animalId)
                .orderByDesc(RescueStory::getCreateTime)
                .list();
        res.put("code", 200);
        res.put("data", list);
        return res;
    }

    /**
     * 添加救助故事
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody RescueStory story) {
        Map<String, Object> res = new HashMap<>();
        story.setCreateTime(LocalDateTime.now());
        rescueStoryService.save(story);
        res.put("code", 200);
        res.put("msg", "添加成功");
        return res;
    }
    /**
     * 上传救助故事图片
     */
    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) throws IOException {
        Map<String, Object> res = new HashMap<>();

        if (file.isEmpty()) {
            res.put("code", 400);
            res.put("msg", "文件为空");
            return res;
        }

        // 上传目录（如：/uploads/stories/）
        String uploadDir = System.getProperty("user.dir") + "/uploads/stories/";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成唯一文件名（避免重复）
        String suffix = "";
        String originalName = file.getOriginalFilename();
        if (originalName != null && originalName.contains(".")) {
            suffix = originalName.substring(originalName.lastIndexOf("."));
        }
        String fileName = "story_" + System.currentTimeMillis() + suffix;

        // 保存文件到本地
        File dest = new File(uploadDir + fileName);
        file.transferTo(dest);

        // 拼接图片访问URL
        String url = "http://localhost:8080/uploads/stories/" + fileName;

        res.put("code", 200);
        res.put("msg", "上传成功");
        res.put("url", url);
        return res;
    }


    /**
     * 修改救助故事
     */
    @PutMapping("/update")
    public Map<String, Object> update(@RequestBody RescueStory story) {
        Map<String, Object> res = new HashMap<>();
        rescueStoryService.updateById(story);
        res.put("code", 200);
        res.put("msg", "修改成功");
        return res;
    }

    /**
     * 删除救助故事
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> delete(@PathVariable Integer id) {
        Map<String, Object> res = new HashMap<>();
        rescueStoryService.removeById(id);
        res.put("code", 200);
        res.put("msg", "删除成功");
        return res;
    }
}
